package com.mlm.mlmapp.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.Constants;
import com.flyco.tablayout.view.OrderFragment;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.adapter.view.PaymentCancelDialog;
import com.mlm.mlmapp.adapter.view.listener.DialogListener;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.interfaces.Prefs_;
import com.mlm.mlmapp.utils.CommonUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.DrawableRes;
import org.androidannotations.annotations.res.StringRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
@EActivity(R.layout.payment_wait)
public class PaymentWaitActivity extends BaseActivity implements HTTPCons {
    AQuery aq;
    AjaxCallback<JSONObject> getPaymentInfoCB;
    PaymentCancelDialog dia;
    @StringRes
    String money;
    @Pref
    Prefs_ pref;
    @Extra
    String orderid;
    @ViewById
    ImageView btn_headimg;
    @ViewById
    TextView tv_dresser;
    @ViewById
    Button tv_post;
    @ViewById
    Button btn_cancel;
    @ViewById
    LinearLayout items;
    @ViewById
    Button btn_date;
    @ViewById
    Button btn_studio;
    @ViewById
    LinearLayout btn_back;
    @ViewById
    Button btn_coupon;
    @ViewById
    TextView tv_money;
    @ViewById
    TextView btn_next;
    @ViewById
    Button btn_username;
    @ViewById
    Button btn_total;
    @ViewById
    Button btn_points;
    @ViewById
    RelativeLayout coupon;
    @ViewById
    RelativeLayout rl_points;
    @ViewById
    CheckBox btn_money;
    @ViewById
    Button btn_paymoney;
    @ViewById
    TextView tv_dingjin1;
    @ViewById
    TextView tv_dingjin3;
    @ViewById
    RelativeLayout dingjin;
    LayoutInflater inflater;
    @ColorRes
    int red;
    @ColorRes
    int blacktext;
    @ColorRes
    int greyborder;
    @ColorRes
    int lightgreytext;
    @DrawableRes
    Drawable red_edge_btn_long;
    private int total = 0;
    int realMoney;
    String depFund;
    int payMoney;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent); // 这一句必须的，否则Intent无法获得最新的数据
        this.orderid = intent.getStringExtra("orderid");
        getOrderInfo();
        // api = WXAPIFactory.createWXAPI(this, "wxb4ba3c02aa476ea1");
    }

    @AfterViews
    void init() {
        // api = WXAPIFactory.createWXAPI(this, "wxb4ba3c02aa476ea1");
        String title = getTitle().toString();
        if (!"".equals(title)) {
            ((TextView) this.findViewById(R.id.tv_title)).setText(title);
        }

        aq = new AQuery(this);
        inflater = LayoutInflater.from(this);

        ((ImageButton) btn_back.getChildAt(0)).setImageResource(R.drawable.payment_close);

        tv_money.setText(getString(R.string.money, total));
        getPaymentInfoCB = new AjaxCallback<JSONObject>() {

            @Override
            public void callback(String url, JSONObject html, AjaxStatus status) {
                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                if (status.getCode() == -103) {
                    Toast.makeText(aq.getContext(), "用户信息异常，请联系客服",
                            Toast.LENGTH_SHORT).show();
                } else {
                    if (status.getCode() != 200) {
                        Toast.makeText(aq.getContext(),
                                "网络异常:" + status.getCode(), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        try {
                            onSuccess(html);
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        };
        getOrderInfo();
    }


    /**
     * send sms authcode request
     *
     * @throws UnsupportedEncodingException
     */
    private void getOrderInfo() {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", pref.loginID().get()));
        pairs.add(new BasicNameValuePair("orderId", orderid));
        CommonUtils
                .postRequest(get_payment_action, aq, getPaymentInfoCB, pairs);
    }

    private void cancelOrderInfo() {
        AjaxCallback<JSONObject> cancelCallback = new AjaxCallback<JSONObject>() {

            @Override
            public void callback(String url, JSONObject html, AjaxStatus status) {
                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                if (status.getCode() == -103) {
                    Toast.makeText(aq.getContext(), "用户信息异常，请联系客服",
                            Toast.LENGTH_SHORT).show();
                } else {
                    if (status.getCode() != 200) {
                        Toast.makeText(aq.getContext(),
                                "网络异常:" + status.getCode(), Toast.LENGTH_SHORT)
                                .show();
                    } else {

                        try {
                            if (html.getBoolean("isSuccess")) {
                                Toast.makeText(aq.getContext(),
                                        "订单已取消!", Toast.LENGTH_SHORT)
                                        .show();
                                Intent intent = new Intent();
                                intent.setAction(OrderFragment.ORDER_REFRESH_FLAG);
                                intent.putExtra("refreshflag", "0");
                                aq.getContext().sendOrderedBroadcast(intent, null);
//                                BookActivity_.intent(PaymentWaitActivity.this).start();
                                PaymentWaitActivity.this.finish();

                            } else {
                                Toast.makeText(aq.getContext(),
                                        html.getString("errors"), Toast.LENGTH_SHORT)
                                        .show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                }
            }
        };

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", pref.loginID().get()));
        pairs.add(new BasicNameValuePair("orderId", orderid));
        CommonUtils
                .postRequest(cancel_order, aq, cancelCallback, pairs);
    }

    void onSuccess(JSONObject obj) throws JSONException {
        aq.id(btn_headimg).image(getJsonString(obj, "iconPhotoUrl"), true,
                true, 200, 0, null, Constants.FADE_IN);
        btn_paymoney.setText(getString(R.string.pay, getJsonInt(obj, "realMoney")));
        realMoney = getJsonInt(obj, "realMoney");
        depFund = getJsonString(obj, "depFund");
        if ("0".equals(getJsonString(obj, "userCouponId"))) {
            coupon.setVisibility(View.GONE);
        }
        if ("0".equals(getJsonString(obj, "integralMoney"))) {
            rl_points.setVisibility(View.GONE);
        } else {
            btn_points.setText(getString(R.string.money1,
                    getJsonInt(obj, "integralMoney")));
        }
        if ("1".equals(getJsonString(obj, "status"))) {
            btn_cancel.setVisibility(View.VISIBLE);
        } else {
            btn_cancel.setVisibility(View.INVISIBLE);
        }

//		couponcount = getJsonInt(obj, "isCoupon");
//		btn_coupon.setText(getString(R.string.coupon_valid, 0));
//		getCouponCountAction();
        // if (couponcount <= 0) {
        // btn_coupon.setTextColor(red);
        // btn_coupon.setClickable(true);
        // } else {
        // btn_coupon.setTextColor(lightgreytext);
        // btn_coupon.setClickable(false);
        //
        // }
//		tv_pointmoney.setText(getString(R.string.money,
//				getJsonInt(obj, "integralMoney")));
//		tv_point.setText(getString(R.string.point, getJsonInt(obj, "integral")));
        btn_coupon.setText(getJsonString(obj, "userCouponName"));
//        btn_points.setText(getJsonString(obj,"userCouponName"));
        btn_username.setText(getJsonString(obj, "userName"));
        btn_date.setText(getJsonString(obj, "appointTimes"));
        tv_dresser.setText(getJsonString(obj, "name"));

        tv_post.setText(getJsonString(obj, "leveName"));
        btn_total.setText(getString(R.string.money,
                getJsonInt(obj, "orderMoney")));
        payMoney = getJsonInt(obj, "payMoney");
        if ("5".equals(getJsonString(obj, "status"))) {
            tv_money.setText(getString(R.string.money, realMoney - payMoney));
        } else {
            tv_money.setText(getString(R.string.money, payMoney));
        }
        tv_dingjin1.setText(getString(R.string.pay,
                getJsonInt(obj, "depFund")));
        tv_dingjin3.setText(getString(R.string.pay, getJsonInt(obj, "realMoney") - getJsonInt(obj, "depFund")));

        if ("2".equals(getJsonString(obj, "isDepfund").toString())) {
            btn_money.setClickable(false);
            btn_money.isChecked();
            btn_money.setChecked(true);
        } else {
            dingjin.setVisibility(View.GONE);
        }
        JSONArray array = getJsonArray(obj, "bookProducts");
        items.removeAllViews();
        for (int i = 0; i < array.length(); i++) {
            final JSONObject temp = array.getJSONObject(i);
            if (!temp.isNull("productName")) {
                View view = inflater.inflate(R.layout.payment_group_item, null);
                ((TextView) view.findViewById(R.id.row_group_item))
                        .setText(getJsonString(temp, "productName"));
                ((TextView) view.findViewById(R.id.row_price))
                        .setText(getString(R.string.money,
                                getJsonInt(temp, "price")));
                items.addView(view);
            }
        }
        JSONObject studio = getJsonObject(obj, "studio");
        btn_studio.setText(getJsonString(studio, "names"));
    }

    @Click
    void btn_cancel() {
        dia = new PaymentCancelDialog(this, new DialogListener() {
            @Override
            public void onApply(JSONObject obj, String clazz) {
                cancelOrderInfo();
                dia.dismiss();

            }

            @Override
            public void onCancel() {

            }
        });
        dia.show();
    }

    @Click
    void btn_money() {
        if (btn_money.isChecked()) {
            tv_money.setText(getString(R.string.pay, Integer.valueOf(depFund)));
        } else {
            tv_money.setText(getString(R.string.pay, payMoney));
        }
    }

    @Click
    void btn_next() {
        PaymentOrderActivity_.intent(PaymentWaitActivity.this)
                .extra("orderid", orderid).start();
        this.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CommonUtils.sendBroadCast(PaymentWaitActivity.this, CollectionsActivity.COLLECTION_REFRESH, "refreshflag", "0");
    }

    @Click
    void btn_back() {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
        Intent data = new Intent();
        setResult(RESULT_CANCELED, data);
        this.finish();
    }

}
